package kt.com.bilin.coin.ui.fragment

import android.os.Bundle
import android.view.View
import com.bilin.coin.R
import com.kingja.loadsir.core.LoadService
import kotlinx.android.synthetic.main.fragment_game.*
import kt.com.bilin.coin.api.API_SERVICE
import kt.com.bilin.coin.api.ApiObserver
import kt.com.bilin.coin.api.toData
import kt.com.bilin.coin.common.showEmptyCallback
import kt.com.bilin.coin.common.showLoadingCallback
import kt.com.bilin.coin.helper.loadsir.LoadSirHelper
import kt.com.bilin.coin.utils.CplUtils.getImei
import kt.com.bilin.coin.utils.CplUtils.getPaccXwdeviceid

class GameFragment : BaseFragment(R.layout.fragment_game) {
    private lateinit var mLoadService: LoadService<*>
    override fun initView(rootView: View?, savedInstanceState: Bundle?) {
        mLoadService = LoadSirHelper.register(root_view) { onReload() }
        tvTitleView.onLeftClickListener = {
            if (webview.canGoBack()) webview.goBack()
        }
    }

    override fun initData(rootView: View?, savedInstanceState: Bundle?) {
        mLoadService.showLoadingCallback()
        onReload()
    }

    private fun onReload() {
        activity?.run {
            getImei { imei ->
                getPaccXwdeviceid { xwdeviceid ->
                    launchUI({ API_SERVICE.cplGetUrl(imei, xwdeviceid).toData() }, ApiObserver(loadService = mLoadService) {
                        if (it.isNullOrEmpty()) {
                            mLoadService.showEmptyCallback()
                        } else {
                            tvTitleView.titleStr = it[0].name.ifEmpty { "游戏" }
                            webview.loadUrl(it[0].url)
                        }
                    })
                }
            }
        }
    }
}